const util = require('../../utils/util');
const MenuService = require('../../service/system/menu.service');

// 获取菜单树状列表
async function listMenuTree(ctx) {
	const menuTree = await MenuService.getMenuTree();
	util.success(ctx, menuTree);
}

// 获取当前用户可见的菜单
async function getUserMenus(ctx) {
	let userId;
	try {
		const decoded = util.decodeToken(ctx); // 假设 decodeToken 返回 { userId }
		if (!decoded || !decoded.userId) {
			return util.fail(ctx, '无法解析用户 ID，Token 无效或缺失');
		}
		userId = decoded.userId;
	} catch (error) {
		return util.fail(ctx, `Token 解析失败: ${error.message}`);
	}

	try {
		const menus = await MenuService.getUserMenus(userId);
		util.success(ctx, menus);
	} catch (error) {
		util.fail(ctx, `获取用户菜单失败: ${error.message}`);
	}
}

// 获取上级目录树
async function getMenuTreeForParent(ctx) {
	const { nodeId } = ctx.request.query;
	const tree = await MenuService.getMenuTreeForParent(nodeId || null);
	util.success(ctx, tree);
}

// 获取单个菜单信息
async function getMenuById(ctx) {
	const { id } = ctx.params;
	const menu = await MenuService.getMenuById(id);
	util.success(ctx, menu);
}

// 获取所有按钮权限
async function getButtonPermissions(ctx) {
	const permissions = await MenuService.getButtonPermissions();
	util.success(ctx, permissions);
}

// 验证菜单权限是否存在
async function checkPermissionExists(ctx) {
	const { permissions, id } = ctx.request.query;

	// 参数校验
	if (!permissions) {
		return util.success(ctx, { permissionCount: 0 }); // 无权限标识时，默认通过
	}

	try {
		const count = await MenuService.checkPermissionExists(permissions, id);
		util.success(ctx, { permissionCount: count });
	} catch (error) {
		util.fail(ctx, `验证权限失败: ${error.message}`);
	}
}

// 获取当前用户的角色
async function getUserRoles(ctx) {
	let userId;
	try {
		const decoded = util.decodeToken(ctx); // 假设 decodeToken 返回 { userId }
		if (!decoded || !decoded.userId) {
			return util.fail(ctx, '无法解析用户 ID，Token 无效或缺失');
		}
		userId = decoded.userId;
	} catch (error) {
		return util.fail(ctx, `Token 解析失败: ${error.message}`);
	}

	try {
		const roles = await MenuService.getUserRoles(userId);
		util.success(ctx, roles);
	} catch (error) {
		util.fail(ctx, `获取用户角色失败: ${error.message}`);
	}
}

// 删除菜单
async function deleteMenus(ctx) {
	const { ids } = ctx.request.body;
	const { userId } = util.decodeToken(ctx);

	try {
		// 执行删除
		const result = await MenuService.deleteMenus(ids, userId);
		if (result.affectedRows === 0) {
			return util.fail(ctx, '没有找到可删除的菜单');
		}
		util.success(ctx, null);
	} catch (error) {
		util.fail(ctx, `删除菜单失败: ${error.message}`);
	}
}

// 新增菜单
async function createMenu(ctx) {
	const params = ctx.request.body;
	const { userId } = util.decodeToken(ctx);

	// 参数校验
	const requiredFields = ['pid', 'sort', 'menuTypeCd', 'title'];
	for (const field of requiredFields) {
		if (!params[field] && params[field] !== '0') {
			return util.fail(ctx, `缺少必填字段: ${field}`);
		}
	}

	try {
		// 根据类型校验额外字段
		const { menuTypeCd } = params;
		if (menuTypeCd === '1002001' || menuTypeCd === '1002002') {
			if (!params.icon) return util.fail(ctx, '目录或菜单需填写图标');
			if (!params.name) return util.fail(ctx, '目录或菜单需填写路由名称');
			if (!params.path) return util.fail(ctx, '目录或菜单需填写路由地址');
		}
		if (menuTypeCd === '1002002' && params.isLink !== 'T') {
			if (!params.component) return util.fail(ctx, '菜单需填写组件路径');
		}
		if ((menuTypeCd === '1002002' || menuTypeCd === '1002003') && params.permissions) {
			const count = await MenuService.checkPermissionExists(params.permissions);
			if (count > 0) return util.fail(ctx, '权限标识已存在');
		}

		// 保存菜单
		const menuId = await MenuService.createMenu(params, userId);
		util.success(ctx, { id: menuId });
	} catch (error) {
		util.fail(ctx, `新增菜单失败: ${error.message}`);
	}
}

//修改数据权限
async function changeDataRole(ctx) {
	const { menuId } = ctx.params;
	const { userId } = util.decodeToken(ctx);

	if (!menuId) {
		return util.fail(ctx, '菜单 ID 无效');
	}

	try {
		// 切换数据权限状态
		const result = await MenuService.changeDataRole(menuId, userId);
		if (result.affectedRows === 0) {
			return util.fail(ctx, '菜单不存在或已被删除');
		}
		util.success(ctx, null);
	} catch (error) {
		util.fail(ctx, `修改数据权限状态失败: ${error.message}`);
	}
}

async function updateMenu(ctx) {
	const {
		id,
		pid,
		path,
		name,
		title,
		icon,
		component,
		redirect,
		sort,
		menuTypeCd,
		permissions,
		isHidden,
		hasChildren,
		isLink,
		isFull,
		isAffix,
		isKeepAlive,
		useDataScope,
		deep,
	} = ctx.request.body;

	// 校验必填字段
	if (!id || !title || !menuTypeCd) {
		return util.fail(ctx, '菜单 ID、标题或菜单类型不能为空');
	}

	try {
		const result = await MenuService.updateMenu({
			id,
			pid,
			path,
			name,
			title,
			icon,
			component,
			redirect,
			sort,
			menuTypeCd,
			permissions,
			isHidden,
			hasChildren,
			isLink,
			isFull,
			isAffix,
			isKeepAlive,
			useDataScope,
			deep,
			updateId: ctx.state.user?.id || 1, // 假设从 Token 获取当前用户 ID，默认 1
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `编辑菜单失败: ${error.message}`);
	}
}
module.exports = {
	listMenuTree,
	getUserMenus,
	getMenuTreeForParent,
	getMenuById,
	getButtonPermissions,
	checkPermissionExists,
	getUserRoles,
	deleteMenus,
	createMenu,
	changeDataRole,
	updateMenu,
};
